package siteflash.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import siteflash.data.SiteFlashPersistenceManage;
import siteflash.helper.Paginator;
import siteflash.model.Game;
import siteflash.model.Paginate;
import siteflash.model.Tag;

public class Search extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
		
        String keySearch = (String) req.getParameter("keysearch");
        
        PersistenceManager psm = SiteFlashPersistenceManage.get().getPersistenceManager();
        //List all tags
        ArrayList<Tag> tags = (ArrayList<Tag>) General.getTags();
        int total = 18;
        
        //Set limit and number page
        int limit = 18;
        String strPage = (String) req.getParameter("page");
        int page = 1;
        if (strPage != null) {
        	page = Integer.parseInt(strPage);
        }
        int start = (page - 1) * limit;
        int end = page * limit;
        
        //List all game
        Query query = psm.newQuery(Game.class);
        query.setFilter("name == nameParam");
        query.setOrdering("name asc");
        query.setRange(start, end);
        query.declareParameters("java.lang.String nameParam");
        List<Game> listResult = (List<Game>) query.execute(keySearch);
        ArrayList<Game> games = new ArrayList<Game>();
        for (int i=0; i < listResult.size(); i++) {
            games.add(listResult.get(i));
        }
        
        //List hot game
        ArrayList<Game> hotGames = (ArrayList<Game>) General.hotGames();
        
        //Paginate
        Paginator paginator = new Paginator();
        paginator.setLimit(limit);
        Paginate paginate = paginator.paginate(page, total);
        
        req.setAttribute("keySearch", keySearch);
        req.setAttribute("pageName", "home");
        req.setAttribute("tags", tags);
        req.setAttribute("games", games);
        req.setAttribute("hotGame", hotGames);
        req.setAttribute("paginate", paginate);
        try {
        	
        	req.setAttribute("title", "Search: " + keySearch + " - Y1S Game");
            req.setAttribute("keyword", "y1s, y1s.org, game directory, flash games, free flash games, online games, play game, fun, flash games online, search game");
            req.setAttribute("description", "Y1s.org Search game info " + keySearch);
        	
            req.getRequestDispatcher("/pages/homepage.jsp").forward(req, resp);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
        }
	}
}
